package org.kernely.test.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.kernely.persistence.service.SessionService;
import org.kernely.test.persistence.ToDo;
import org.osgi.service.component.ComponentContext;

/**
 * Provides methods about UserDetails management
 */
public class TodoDao {
	/**
	 * SessionService service
	 */
	private static SessionService service;
	
	/**
	 * The user details dao instance
	 */
	private static TodoDao instance;
	
	/**
	 * Store the user details dao instance 
	 * @return the user details dao
	 */
	public static TodoDao getInstance() {
		return instance;
	}
	/**
	 * Set the persistence session service
	 * @param sessionService the session service to set
	 */
	public final void setPersistenceService(SessionService sessionService) {
		service = sessionService;
	}

	/**
	 * Activate the component
	 * @param ctxt the activation context
	 */
	final protected void activate(ComponentContext ctxt) {
		instance = this;
	}

	
	/**
	 * Fill the table with all ToDoTasks registered
	 */
	@SuppressWarnings("unchecked")
	public final List<ToDo> getAll(){
		//call the session factory to get all the messages
		Session session = service.getSessionFactory().openSession();
		Transaction t = session.beginTransaction();
		List<ToDo> messages = (List<ToDo>)session.createCriteria(ToDo.class).list();
		t.commit();
		if(session.isOpen()){
			session.close();
		}
		return messages;
	}
	/**
	 * Delete all messages
	 */
	@SuppressWarnings("unchecked")
	public final void deleteAll(){
		//call the session factory to get all the messages
		Session session = service.getSessionFactory().openSession();
		Transaction t = session.beginTransaction();
		List<ToDo> messages = (List<ToDo>)session.createCriteria(ToDo.class).list();
		t.commit();
		for (ToDo message : messages){
			session.delete(message);
		}
		if(session.isOpen()){
			session.close();
		}
	}
	
	/**
	 * Saves a todo
	 * @param message the message to save
	 * @return the id of the inserted message
	 */
	public final int save(ToDo message){
		// Get the hibernate session
		Session databaseSession = service.getSessionFactory().openSession();
		// Open the transaction
		Transaction t = databaseSession.beginTransaction();
		// Persists the message
		databaseSession.save(message);
		int id = (Integer) databaseSession.getIdentifier(message);
		
		t.commit();
		databaseSession.flush();
		if(databaseSession.isOpen()){
			databaseSession.close();
		}
		return id;
	}
	
	
	
}
